package com.hfb.mashibing.alip8.juc.c020;


import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;

/**
 * 读写锁:排他锁/互斥锁/独占锁(无论读写)
 *  读锁——共享锁
 *  写锁——排他锁/互斥锁/独占锁
 *
 *
 *  扩展：StampedLock
 */

public class T10_TestReadWriteLock {
    // 排他锁/互斥锁/独占锁(无论读写)
    static Lock lock = new ReentrantLock();
    private static int value;

    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();


    public static void read(Lock lock)   {
        try {
            // 模拟读取操作
            lock.lock();
            TimeUnit.MILLISECONDS.sleep(1000);
            System.out.println("read over！" + value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally { lock.unlock();}
    }
    public static void write(Lock lock, int v)   {
        try {
            // 模拟写操作
            lock.lock();
            TimeUnit.MILLISECONDS.sleep(1000);
            value = v;
            System.out.println("write over！"+ value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally { lock.unlock();}
    }
    public static void main(String[] args) {
//        Runnable readR = ()->read(lock); // 耗时:20 秒
        Runnable readR = ()->read(readLock); // 耗时：2秒

        Runnable writeR = ()->read(writeLock);

        for (int i = 0; i < 18; i++) new Thread(readR).start();
        for (int i = 0; i < 2; i++) new Thread(writeR).start();

    }
}
